/**
 * 剑指 Offer 59 - II. 队列的最大值
 * https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/
 */

function MaxQueue() {
  this.queue = [];
  this.max = -1;
  this.dirty = true;
}

/**
 * @return {number}
 */
MaxQueue.prototype.max_value = function () {
  if (!this.queue.length) {
    return -1;
  }
  if (!this.dirty) {
    return this.max;
  }
  // eslint-disable-next-line prefer-spread
  this.max = Math.max.apply(Math, this.queue);
  this.dirty = false;
  return this.max;
};

/**
 * @param {number} value
 * @return {void}
 */
MaxQueue.prototype.push_back = function (value) {
  this.queue.push(value);
  if (!this.dirty) {
    this.max = Math.max(this.max, value);
  } else if (this.queue.length === 1) {
    this.max = value;
    this.dirty = false;
  }
};

/**
 * @return {number}
 */
MaxQueue.prototype.pop_front = function () {
  if (!this.queue.length) {
    return -1;
  }
  const value = this.queue.shift();
  if (!this.dirty) {
    if (value === this.max) {
      this.dirty = true;
    }
  }
  return value;
};

let queue;

queue = new MaxQueue();
queue.push_back(1);
queue.push_back(2);
console.log(queue.max_value() === 2);
console.log(queue.pop_front() === 1);
console.log(queue.max_value() === 2);

queue = new MaxQueue();
console.log(queue.pop_front() === -1);
console.log(queue.max_value() === -1);
